#include "../include/reader.h"

ostream& operator <<(ostream& oo, const DocItem& item) {
  oo << "title: " << item.title << endl << "url: " << item.url << endl
      << "content: " << item.content << endl;
  return oo;
}

istream& operator >>(istream& in, DocItem& item) {
  string line;
  string::size_type pos;
  do {
    getline(in, line);
  } while (line.empty() && !in.eof());

  if (in.eof())
    return in;

  if (line == "<doc>")
    ; //start
  getline(in, line); //url
  pos = line.find("</url>");
  item.url = line.substr(5, pos - 5);

  getline(in, line); //docno
  getline(in, line); //title
  pos = line.find("</contenttitle>");
  item.title = line.substr(14, pos - 14);
  string content;
  while (getline(in, line)) {
    if (line == "</doc>") //end
      break;
    content += line;
  }
  pos = content.find("</content>");
  item.content = content.substr(9, pos - 9);
  return in;
}

Reader::Reader() {
}

Reader::~Reader() {
}

int Reader::read_next_item(DocItem& item) {
  if (!has_loaded_)
    return -1;
  if (!this->file_.eof())
    file_ >> item;
  return !file_.eof();
}


bool Reader::load_file(const char* fname) {
  if (this->file_.is_open()) {
    file_.close();
    file_.clear();
  }
  file_.open(fname);
  if (!file_.is_open())
    return false;
  char c;
  file_.get(c);
  if (c == '\0') {
    cerr << "open file error" << fname << endl;
    return false;
  } else
    file_.seekg(0);
  has_loaded_ = true;
  return true;
}

